﻿using System.ComponentModel;
using K9Nano.Application.Dtos;
using K9Nano.Application.Logging;
using K9Nano.Exceptions;
using K9Nano.Logging;
using Microsoft.AspNetCore.Mvc;

namespace K9Nano.AspNetCore.Controllers;

[Route("admin/api/log")]
[Description("系统日志管理接口")]
public class LogController(ILogAppService service) : ApiControllerBase
{
    ///// <summary>
    ///// 分页查询系统日志
    ///// </summary>
    ///// <param name="sourceContext">日志源，模糊匹配</param>
    ///// <param name="level">日志级别，精准匹配</param>
    ///// <param name="from">起始时间</param>
    ///// <param name="to">截止时间</param>
    ///// <param name="pageIndex">页码</param>
    ///// <param name="pageSize">分页大小</param>
    ///// <returns></returns>
    //[HttpGet("system")]
    //[Description("分页查询系统日志")]
    //public async Task<PagedResultDto<SystemLog>> GetSystemLogs(string? sourceContext, string? level,
    //    DateTime from, DateTime to, int pageIndex, int pageSize)
    //{
    //    if (to <= from) throw FriendlyException.BadRequest("截止时间必须大于起始时间");
    //    if (pageIndex < 1) throw FriendlyException.BadRequest("页面不能小于1");
    //    if (pageSize < 1) throw FriendlyException.BadRequest("分页大小");

    //    var (total, items) = await systemLogStore.QueryAsync(sourceContext, level, from, to, pageIndex, pageSize, HttpContext.RequestAborted);
    //    return new PagedResultDto<SystemLog>(total, items);
    //}

    ///// <summary>
    ///// 按时段删除系统日志
    ///// </summary>
    ///// <param name="from">起始时间</param>
    ///// <param name="to">截止时间</param>
    ///// <returns>删除的数据量</returns>
    //[HttpDelete("system")]
    //[Description("按时段删除系统日志")]
    //public async Task<int> DeleteSystemLogs([FromQuery] DateTime from, [FromQuery] DateTime to)
    //{
    //    return await service.DeleteAsync(from, to, HttpContext.RequestAborted);
    //}

    /// <summary>
    /// 分页查询HTTP日志
    /// </summary>
    [HttpGet("http")]
    [Description("分页查询HTTP日志")]
    public async Task<PagedResultDto<ApiLogEntity>> GetHttpLogs([FromQuery]ApiLogPagedInput dto)
    {
        if (dto.To <= dto.From) throw FriendlyException.BadRequest("截止时间必须大于起始时间");
        if (dto.PageIndex < 1) throw FriendlyException.BadRequest("页面不能小于1");
        if (dto.PageSize < 1) throw FriendlyException.BadRequest("分页大小");

        var result = await service.QueryAsync(dto, HttpContext.RequestAborted);
        return result;
    }

    /// <summary>
    /// 按时段删除HTTP日志
    /// </summary>
    /// <param name="from">起始时间</param>
    /// <param name="to">截止时间</param>
    /// <returns>删除的数据量</returns>
    [HttpDelete("http")]
    [Description("按时段删除HTTP日志")]
    public async Task<int> DeleteHttpLogs([FromQuery] DateTime from, [FromQuery] DateTime to)
    {
        return await service.DeleteAsync(from, to, HttpContext.RequestAborted);
    }
}
